﻿using System;
using System.Collections;
using UnityEngine;

namespace Component.Tools
{
    public class NodeGroup : MonoBehaviour
    {
        [SerializeField] private float nodeWidth;
        [SerializeField] private float nodeHeight;
        [SerializeField] private float verticalSpacing;
        [SerializeField] private float horizontalSpacing;
        [SerializeField] private int horizontalMaximum;

        private void Start()
        {
            // verticalSpacing += nodeHeight;
            // horizontalSpacing += nodeWidth;
            transform.position -= (Vector3.right * horizontalSpacing / 2 + Vector3.up * verticalSpacing / 2);
            
            // StartCoroutine(CheckNode());
        }

        private void OnEnable()
        {
            StopCoroutine(CheckNode());
            StartCoroutine(CheckNode());
        }

        private IEnumerator CheckNode()
        {
            int currentCount = transform.childCount;

            while (true)
            {
                // if (currentCount != transform.childCount)
                // {
                    // for (int i = currentCount < transform.childCount ? currentCount : 0; i < transform.childCount; i++)

                    for (int i = 0; i < transform.childCount; i++)
                    {
                        Vector3 position = (i % horizontalMaximum + 1) * horizontalSpacing * Vector3.right +
                                           (i / horizontalMaximum + 1) * verticalSpacing * Vector3.up;
        
                        var t = transform.GetChild(i);
                        t.position = transform.position;
                        t.position += position;
                    }
                    currentCount = transform.childCount;
                // }
                yield return new WaitForSeconds(Time.deltaTime);
            }

        }

        public static void FormatNodes(Transform parent, int horizontalMaximum, float horizontalSpacing, float verticalSpacing)
        {
            
            parent.position -= (Vector3.right * horizontalSpacing / 2 + Vector3.up * verticalSpacing / 2);
            for (int i = 0; i < parent.childCount; i++)
            {
                Vector3 position = (i % horizontalMaximum + 1) * horizontalSpacing * Vector3.right +
                                   (i / horizontalMaximum + 1) * verticalSpacing * Vector3.up;
        
                var t = parent.GetChild(i);
                t.position = parent.position;
                t.position += position;
            }
        }
    }
}